﻿using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace Chimp.Core
{
    public class ParticleLine : ChimpParticle
    {
        private bool First = true;

        public ParticleLine()
        {
            Z = 0.01f + (float) new Random().NextDouble()*0.03f;
        }

        public Vector2 LastPos { get; set; }

        public override ChimpParticle RequestNew()
        {
            return new ParticleLine();
        }

        public override void OnDraw(Vector2 pos)
        {
            //pos = DrawPos;

            pos = GetPos(DrawPos);
            if (First)
            {
                LastPos = pos;
                First = false;
            }

            if (pos.X < 0 || pos.X > ChimpApp.W || pos.Y < 0 || pos.Y > ChimpApp.H)
            {
                //LastPos = pos;
                // return;
            }
            float tf = 0.3f;
            if ((pos - LastPos).LengthFast > 50)
            {
                LastPos = Vector2.Lerp(LastPos, pos, tf);
            }

            float cv = 0.05f + (Z*0.8f);


            ChimpDraw.BlendMode = ChimpBlend.Alpha;
            ChimpDraw.Rect(new Vector4(pos.X - 1, pos.Y - 1, 2, 2), new Vector4(cv, cv, cv, cv));


            GL.LineWidth(2);


            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Disable(EnableCap.AlphaTest);

            //LastPos = LastPos - (pos - LastPos) * 4.0f;


            GL.Begin(BeginMode.Lines);

            GL.Color4(new Vector4(cv*0.2f, cv*0.2f, cv*0.2f, cv*0.2f));
            GL.Vertex2(LastPos);


            GL.Color4(new Vector4(cv, cv, cv, cv));
            GL.Vertex2(pos);

            GL.End();


            LastPos = Vector2.Lerp(LastPos, pos, tf);
        }
    }
}